package com.study.spmongodb.book.wwj.char03;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author MI
 * @version 1.0
 * @date 2020/11/24 19:24
 */
public class FightQueryExample {
    private static final List<String> fightCompany = Arrays.asList("CSA", "CEA", "HNA");

    public static void main(String[] args) {
        final List<String> results = search("SH", "BJ");
        System.out.println("=============result============");
        results.forEach(System.out::println);

    }

    private static List<String> search(String original, String dest) {
        final ArrayList<String> result = new ArrayList<>();
        //创建查询航班信息的线程列表
        final List<FightQueryTask> task = fightCompany.stream().map(f -> createSearchTask(f, original, dest))
                .collect(Collectors.toList());
        //分别启动这几个线程
        task.forEach(Thread::start);

        // 分别调用每一个线程的join方法，阻塞当前线程
        task.forEach(t -> {
            try {
                t.join();
            } catch (InterruptedException e) {
            }
        });
        //在此之前，当前线程会阻塞，获取每一个线程的查询结果，
        task.stream().map(FightQuery::get).forEach(result::addAll);
        return result;
    }

    private static FightQueryTask createSearchTask(String fight, String original, String dest) {
        return new FightQueryTask(fight, original, dest);
    }
}
